package cn.java79.springboot.zsb.service;

import cn.java79.springboot.zsb.dao.UserMapper;
import cn.java79.springboot.zsb.entity.User;
import cn.java79.springboot.zsb.util.Md5Util;
import cn.java79.springboot.zsb.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

/**
 * @author oldliu
 * @since 1.0
 */
@Service
@CacheConfig(cacheNames = "user")//缓存的名字
@Cacheable(keyGenerator = "keyg")//指定key生成器
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    //清除缓存
    @CacheEvict(allEntries = true)
    @Override
    public boolean save(User entity) {
        entity.setPass(Md5Util.encode(entity.getPass()));
        return super.save(entity);
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }
    @CacheEvict(allEntries = true)
    @Override
    public boolean updateById(User entity) {
        return super.updateById(entity);
    }

    @Override
    public List<User> search(String sname, String phone, String school) {
        QueryWrapper<User> q=new QueryWrapper<>();
        q.like(!StrUtil.isBlank(sname),"sname",sname);
        q.like(!StrUtil.isBlank(phone),"phone",phone);
        q.like(!StrUtil.isBlank(school),"school",school);

        return super.list(q);
    }


    @Override
    public Page<User> search(String sname, String phone, String school, int pageNo, int pageSize) {
        Page<User> p=new Page<>(pageNo,pageSize);
        QueryWrapper<User> q=new QueryWrapper<>();
        q.like(!StrUtil.isBlank(sname),"sname",sname);
        q.like(!StrUtil.isBlank(phone),"phone",phone);
        q.like(!StrUtil.isBlank(school),"school",school);
        Page<User> page = super.page(p, q);
        return page;
    }

    @Override//检查手机号是否重复~！
    public boolean checkPhone(Long id ,String phone) {
        QueryWrapper<User> q=new QueryWrapper<>();
        q.ne(id!=null,"id",id);
        q.eq("phone",phone);
        int count = super.count(q);
        return count>0;
    }

    @Override
    public boolean updatePass(Long id, String newPass) {
        User user=new User();
        user.setPass(Md5Util.encode(newPass));
        user.setId(id);
        super.updateById(user);
        return false;
    }
}
